<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="sku信息" prop="skuInfo">
        <el-input
          v-model="queryParams.skuInfo"
          placeholder="请输入sku信息，如：年卡-30次-标砖版"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="卡号" prop="cardNumber">
        <el-input
          v-model="queryParams.cardNumber"
          placeholder="请输入卡号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="卡类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择卡类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CARD_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="卡状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择卡状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CARD_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="门店类型" prop="outletType">
        <el-select
          v-model="queryParams.outletType"
          placeholder="请选择门店类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OUTLET_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="门店id" prop="outletId">
        <el-input
          v-model="queryParams.outletId"
          placeholder="请输入门店id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="激活用户" prop="userId">
        <el-input
          v-model="selectedUserName"
          placeholder="请选择激活用户"
          clearable
          readonly
          @clear="handleClearUser"
          class="!w-240px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="启用状态" prop="enable">
        <el-select
          v-model="queryParams.enable"
          placeholder="请选择启用状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['dc:card:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['dc:card:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['dc:card:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="id" align="center" prop="id" width="80" />
      <!-- <el-table-column label="对应的配送卡商品spuId" align="center" prop="spuId" /> -->
      <el-table-column label="sku信息" align="center" prop="skuId" :formatter="formatProperties" width="220" />
      <el-table-column label="卡号" align="center" prop="cardNumber" width="150" />
      <el-table-column label="卡密" align="center" prop="cardPassword" width="150" />
      <el-table-column label="卡类型" align="center" prop="type" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CARD_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="卡状态" align="center" prop="status" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CARD_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="门店类型" align="center" prop="outletType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OUTLET_TYPE" :value="scope.row.outletType" />
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center" prop="outletName" width="150" />
      <el-table-column label="激活用户" align="center" prop="userName" width="120" />
      <el-table-column label="启用状态" align="center" prop="enable" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.enable" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" width="260" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['dc:card:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['dc:card:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleDestroy(scope.row)"
          >
            销毁
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['dc:card:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CardForm ref="formRef" @success="getList" />

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />

  <!-- 详情弹窗 -->
  <CardDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CardApi, CardVO } from '@/api/dc/card'
import CardForm from './CardForm.vue'
import UserSelectDialog from './UserSelectDialog.vue'
import CardDetail from './CardDetail.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import type { UserVO } from '@/api/member/user'

/** 卡片列表 列表 */
defineOptions({ name: 'Card' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CardVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  spuId: undefined,
  skuInfo: undefined,
  cardNumber: undefined,
  cardPassword: undefined,
  type: undefined,
  status: undefined,
  outletType: undefined,
  outletId: undefined,
  userId: undefined as number | undefined,
  enable: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const userDialogRef = ref() // 用户选择弹窗
const selectedUserName = ref('') // 选中的用户名称
const detailRef = ref() // 详情弹窗

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 复制查询参数，排除skuInfo（前端过滤）
    const apiParams = { ...queryParams }
    const skuInfoFilter: string | undefined = apiParams.skuInfo as string | undefined
    delete apiParams.skuInfo
    
    const data = await CardApi.getCardPage(apiParams)
    let resultList = data.list
    
    // 前端根据skuInfo过滤
    if (skuInfoFilter && skuInfoFilter.trim()) {
      resultList = resultList.filter((item: CardVO) => {
        if (!item.properties || item.properties.length === 0) {
          return false
        }
        // 拼接properties的valueName
        const skuInfoStr = item.properties.map(p => p.valueName).join('-')
        // 模糊匹配
        return skuInfoStr.includes(skuInfoFilter.trim())
      })
    }
    
    list.value = resultList
    total.value = skuInfoFilter ? resultList.length : data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedUserName.value = '' // 清空用户名称
  handleQuery()
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserVO) => {
  queryParams.userId = user.id as number
  selectedUserName.value = user.nickname || user.name || user.mobile || ''
}

/** 清空用户选择 */
const handleClearUser = () => {
  queryParams.userId = undefined
  selectedUserName.value = ''
}

/** 查看详情 */
const openDetail = (row: CardVO) => {
  detailRef.value?.open(row)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 销毁卡片操作 */
const handleDestroy = async (row: CardVO) => {
  try {
    // 判断卡片状态
    if (row.status === 5) {
      message.warning('该卡片已经销毁，无需重复操作')
      return
    }
    if (row.status !== 4) {
      message.warning('只有回收状态的卡片才可以销毁')
      return
    }
    
    // 销毁的二次确认
    await message.confirm('确定要销毁该卡片吗？销毁后卡片状态将变为已销毁', '提示')
    // 调用更新接口，将status改为5
    const updateData = {
      ...row,
      status: 5
    } as CardVO
    await CardApi.updateCard(updateData)
    message.success('销毁成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CardApi.deleteCard(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除卡片列表 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await CardApi.deleteCardList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: CardVO[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 格式化 properties 显示 */
const formatProperties = (row: any) => {
  if (!row.properties || !Array.isArray(row.properties) || row.properties.length === 0) {
    return row.skuId || '-'
  }
  return row.properties.map((item: any) => item.valueName).join('-')
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CardApi.exportCard(queryParams)
    download.excel(data, '卡片列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>